<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\traits;

use app\admin\controller\system\Uploadfile;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use EasyAdmin\upload\Uploadfile AS UploadfileS;
use jianyan\excel\Excel;
use Symfony\Component\VarDumper\Tests\Fixture\DumbFoo;
use think\facade\Db;

/**
 * 后台CURD复用
 * Trait Curd
 * @package app\admin\traits
 */
trait Curd
{


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        empty($row) && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFileds)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="导入")
     */
    public function imports()
    {
        $file = request()->file('file');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile('file', $file);
        //获取文件路径
        $path = public_path() . 'public/' . $savename;
        $result = Excel::import($path);
        array_shift($result);
        $result = array_values($result);
        $admin = session('admin');
        $venues_id = $admin['id'] != 1 ? $admin['id'] : 0;
        foreach ($result as $k => $val) {
            $data[$k]['name'] = $val[0];
            $data[$k]['mobile'] = $val[1];
            $data[$k]['id_card'] = $val[2];
            $data[$k]['sex'] = $val[3];
            $data[$k]['unit'] = $val[4];
            $data[$k]['section'] = $val[5];
            $data[$k]['status'] = 1;
            $data[$k]['venues_id'] = $venues_id;
        }
        if (!$data) $this->error('无数据');
        try {
            $save = $this->model->saveAll($data);
        } catch (\Exception $e) {
            return ['code' => 0, 'message' => '导入失败'];
        }
        if ($save) {
            unlink($path);
            return ['code' => 1, 'message' => '导入成功'];
        }
        return ['code' => 0, 'message' => '导入失败'];
    }

    /**
     * @NodeAnotation(title="导入图片")
     */
    public function batpictures()
    {
       $file = request()->file('file');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('public')->putFile('file', $file);
        //获取文件路径
        $path = public_path() . 'public/' . $savename;
        $zip = new \ZipArchive();//新建一个ZipArchive的对象
        $zippath = public_path() . 'public/file/zips/';
        if ($zip->open($path) === TRUE) {
            $zip->extractTo($zippath);//假设解压缩到在当前路径下images文件夹的子文件夹php
            $zip->close();//关闭处理的zip文件
        }
        //获取解压后的文件
        $getDirContent = getDirContent($zippath);
        foreach ($getDirContent as $k => $v) {
            $result = txcossc('/file/zips/' . $v, public_path() . 'public/file/zips/' . $v);
            $name = explode('@', $v)[0];
            $mobile = explode('.', explode('@', $v)[1])[0];
            $url = $result['url'];
            $tencentcloud = new \Tencentcloud();
            $tencentcloud = $tencentcloud->createPerson($name, $mobile, $url);
            if (isset($tencentcloud['FaceId']) && $tencentcloud['FaceId']) {
                Db::name('user')->where(['mobile' => $mobile])->update(['images' => $result['url']]);
            }

        }
        return ['code' => 1, 'message' => '导入图片成功'];
       
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFileds)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

}